<template>
  <div class="login-form">
    <LoginFormTitle v-show="getShow" class="enter-x" />
    <Form :wrapperCol="{ span: 24 }" class="p-4 enter-x" ref="formRef" v-show="getShow" :model="formState">
      <FormItem
        class="enter-x"
        name="username"
        :rules="[
          {
            required: true,
            message: '用户名不能为空',
          },
        ]"
      >
        <Input v-model:value="formState.username" placeholder="请输入用户名/手机号/邮箱" @keyup.enter="nextFocus" />
      </FormItem>
      <FormItem
        class="enter-x"
        name="password"
        :rules="[
          {
            required: true,
            message: '密码不能为空',
          },
        ]"
      >
        <InputPassword
          ref="pass"
          v-model:value="formState.password"
          placeholder="请输入密码"
          @keyup.enter="handleLogin"
        />
      </FormItem>
      <FormItem name="verificationCode" :rules="[]">
        <div class="md:flex">
          <VerificationCode
            class="w-100"
            buttonName="发送"
            :selectOptions="selectOptions"
            :buttonFunction="sendVerificationCodeHandler"
            :limitTimer="50"
            ref="verificationCodeRef"
          />
        </div>
      </FormItem>
      <FormItem>
        <Checkbox v-model:checked="formState.remember">记住用户名</Checkbox>
        <Checkbox v-model:checked="formState.privacy">阅读并同意</Checkbox>
        <a @click="handleInfo">《隐私声明》</a>
      </FormItem>
      <FormItem class="enter-x">
        <Button
          type="primary"
          :disabled="!formState.privacy"
          @click="handleLogin"
          size="large"
          block
          :loading="loading"
        >
          {{ t('routes.common.login.loginButton') }}
        </Button>
      </FormItem>
      <FormItem class="enter-x">
        <Button size="large" block @click="setLoginState(LoginStateEnum.REGISTER)">
          {{ t('routes.common.login.registerButton') }}
        </Button>
      </FormItem>
    </Form>
  </div>
</template>

<script lang="ts" setup>
import { ref, unref, computed, reactive } from 'vue';
import { getLocalUserName, setLocalUserName, useLoginState, LoginStateEnum } from './useLogin';
import { Form, Input, InputPassword, Button, Checkbox } from 'ant-design-vue';
import { useI18n } from 'vue-i18n';
import { usePermissionStoreWithOut } from '/@/store/modules/permission';
import LoginFormTitle from './LoginFormTitle.vue';
import VerificationCode from '/@/components/VerificationCode/VerificationCode.vue';

import { transformEnvToDev } from '/@/utils/helper/envTransfrom';
import { sendLoginVerificationCode } from '/@/api/sys/userInfo';

const verificationCodeRef = ref('verificationCodeRef');
const FormItem = Form.Item;

const selectOptions = ref([
  {
    label: '手机',
    value: 'PHONE',
  },
  {
    label: '邮箱',
    value: 'EMAIL',
  },
]);

interface FormState {
  username: string;
  password: string;
  remember: boolean;
  privacy: boolean;
  isDisabled: boolean;
}

const { t } = useI18n();
const loading = ref(false);
const formState = reactive<FormState>({
  username: getLocalUserName(),
  password: '',
  remember: true,
  privacy: true,
  isDisabled: false,
});
const formRef = ref();
const pass = ref();
const { setLoginState, getLoginState } = useLoginState();

const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN);
const permissionStore = usePermissionStoreWithOut();

const nextFocus = () => {
  pass.value.focus();
};

async function handleLogin() {
  try {
    loading.value = true;
    // 记住账号
    if (formState.remember) {
      setLocalUserName(formState.username);
    } else {
      setLocalUserName('');
    }
    // 登录时清除所有菜单类的浏览器缓存
    const userInfo = await permissionStore.fetchUserInfo({
      userName: formState.username,
      password: formState.password,
      verificationCode: verificationCodeRef.value.getVerificationCode(),
    });
    transformEnvToDev(userInfo.location, '', '', 'replace');
  } catch (error) {
    return error;
  } finally {
    loading.value = false;
  }
}

const emit = defineEmits(['show']);
const handleInfo = () => {
  emit('show', true);
};

const sendVerificationCodeHandler = (options: any) => {
  sendLoginVerificationCode({ typeEnum: options, userName: formState.username });
};
</script>

<style lang="less" scoped>
.login-form {
  width: 400px;
  border-radius: 5px;
  padding: 20px 0 0 0;
  background: white;

  .ant-form {
    width: 400px;
    font-size: 12px;
    color: dimgray;
    margin-bottom: 5px;
  }
}
</style>
